package xml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * Generates the xml output and writes it into a xml file
 * @author Daniel Mohr, Daniela Grammlich
 */
public class XMLGenerator {

	private Document doc;
	private Element root;
	private Transformer trans;
	private StreamResult result;
	private DOMSource source;

	private int childNumber = 0;

	public XMLGenerator(){                 
		try {
			DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder;
			docBuilder = dbfac.newDocumentBuilder();
			doc = docBuilder.newDocument();

			TransformerFactory transfac = TransformerFactory.newInstance();
			trans = transfac.newTransformer();
			trans.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml");
			trans.setOutputProperty(OutputKeys.METHOD, "xml");
			trans.setOutputProperty(OutputKeys.INDENT, "yes");

			FileOutputStream os = new FileOutputStream(new File("vector.xml"));
			result = new StreamResult(os);
			source = new DOMSource(doc);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		root = doc.createElement("root");
		doc.appendChild(root);
	}

	/**
	 * Appends the xml output as a child
	 * @param String the name of the element
	 * @param int the value of the element
	 * @param Element the parent element
	 */
	public void appendXml(String name, int value, Element parent){                
		if(doc != null){
			Element el = doc.createElement(name);
			el.appendChild(doc.createTextNode(String.valueOf(value)));
			parent.appendChild(el);
		}
	}

	/**
	 * Appends the xml output as a child
	 * @return the element
	 */
	public Element appendXml(){
		Element el = null;
		if(doc != null){
			el = doc.createElement("child");
			el.setAttribute("movement", String.valueOf(childNumber));
			root.appendChild(el);
			childNumber++;
		}
		return el;
	}

	/**
	 * Transform the XML Source to a Result
	 */
	public void writeXML() {
		try {
			trans.transform(source, result);
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}     

}